import {
  _decorator,
  CCInteger,
  Color,
  Component,
  instantiate,
  Label,
  Node,
  Sprite,
  Prefab,
} from 'cc'
const { ccclass, property } = _decorator
import { DataManager } from './DataManager'
import { COMPLETE_IDIOMS, GAME_STATUS } from './Events'
import { GAME_EVENT_ENUM, GAME_STATUS_ENUM } from './Enums'
import { shuffleArray } from '../Utils'

@ccclass('IdiomsManager')
export class IdiomsManager extends Component {
  // 单词区域
  @property(Node)
  idiomArea: Node = null!
  // 列预制体
  @property(Prefab)
  Column: Prefab = null!
  // 单词预制体
  @property(Prefab)
  Idiom: Prefab = null!

  // 列数
  @property(CCInteger)
  columnCount: number = 6
  // 每列的idiom数量
  @property(CCInteger)
  idiomPerColumn: number = 5

  protected onLoad(): void {
    COMPLETE_IDIOMS.on(GAME_EVENT_ENUM.CHANGE_IDIOM, this.updateIdiomColor, this)
    GAME_STATUS.on(GAME_STATUS_ENUM.RUNNING, this.reStart, this)
  }
  start() {
    this.generateIdioms()
  }
  generateIdioms() {
    DataManager.inst.idiomNodes = []
    const shuffleIdioms = shuffleArray(DataManager.inst.idioms)
    let idiomIndex = 0

    for (let col = 0; col < this.columnCount; col++) {
      const columnNode = instantiate(this.Column)
      this.idiomArea.addChild(columnNode)

      for (let row = 0; row < this.idiomPerColumn; row++) {
        const idiomNode = instantiate(this.Idiom)
        idiomNode.name = shuffleIdioms[idiomIndex]
        DataManager.inst.idiomNodes.push(idiomNode)
        columnNode.addChild(idiomNode)

        // 设置 label 文本
        const label = idiomNode.getComponentInChildren(Label)
        if (label && idiomIndex < shuffleIdioms.length) {
          label.string = shuffleIdioms[idiomIndex]
          idiomIndex++
        }
      }
    }
  }

  updateIdiomColor(completedIdiom: string) {
    // 检查并记录已完成的成语
    if (!DataManager.inst.completedIdioms.includes(completedIdiom)) {
      DataManager.inst.completedIdioms.push(completedIdiom)
      // 遍历所有 Column -> Idiom -> Label，找到匹配项并修改颜色
      for (const columnNode of this.idiomArea.children) {
        for (const idiomNode of columnNode.children) {
          const label = idiomNode.getComponentInChildren(Label)
          if (label && label.string === completedIdiom) {
            const bgSprite = idiomNode.getComponent(Sprite) // 获取背景 Sprite
            if (bgSprite) {
              // 设置淡蓝色背景
              bgSprite.color = new Color(173, 216, 230) // 淡蓝色 (Light Blue)
            }
          }
        }
      }
      if (
        DataManager.inst.completedIdioms.length === DataManager.inst.idioms.length ||
        DataManager.inst.completedIdioms.length === 10
      ) {
        GAME_STATUS.emit(GAME_STATUS_ENUM.COMPLETE)
      }
    }
  }
  // 重新开始后清除节点
  reStart() {
    this.idiomArea.removeAllChildren()
    this.generateIdioms()
  }
}
